﻿using BaseDll;
using CommonDlg;
using CommonTools;
using log4net;
using StationDemo.Properties;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using Language;

namespace StationDemo
{

    
    public partial class Form_MainParamSet: UIPage,IUserRightSwitch
    {
  
        public Form_MainParamSet()
        {
            InitializeComponent();
        }
        //参数表的 各列索引
        private const int  nIndexOfMax  = 3;
        private const int  nIndexOfMin = 4;
        private const int  nIndexOfVal = 2;
        private const int  nIndexOfClass = 6;
        private const int nIndexOfRight = 5;
        private const int  nIndexOfName = 0;
        private const int  nIndexOfUnit = 1;
        private const int  nIndexOfbIsStartCheck = 7;

        public UserRight userRight
        {
            get;
            set;
        }   
        //更新分类信息
        void UpdataParamDataGridViewClass(User CurrentUser)
        {

            userRight = CurrentUser._userRight;
            dataGridView_Param.Rows.Clear();
            ParamSetMgr.GetInstance().ClearAllParamClassList();
            Dictionary<string, ParamSet> allparam = ParamSetMgr.GetInstance().GetFields<ParamSet>(Param_System.Instance);
            foreach (var item in allparam)
            {
                ParamSetMgr.GetInstance().AddParamClass(item.Value._ParamClass);
            }

            List<string> listParamList = ParamSetMgr.GetInstance().GetParamClassList();
            DataGridViewComboBoxColumn combox = (DataGridViewComboBoxColumn)dataGridView_Param.Columns[6];
            combox.Items.Clear();
            foreach (var temp in listParamList)
            {
                if (dataGridView_Param.Columns[nIndexOfClass] is DataGridViewComboBoxColumn)
                {
                    combox.Items.Add(temp);
                }
            }
            treeView_ProdutFile.Nodes[0]?.FirstNode?.Nodes.Clear();
            if (treeView_ProdutFile.Nodes[0].FirstNode != null && treeView_ProdutFile.Nodes[0].FirstNode.Name != null && treeView_ProdutFile.Nodes[0].FirstNode.Text != "")
            {
                List<string> classList = ParamSetMgr.GetInstance().GetParamClassList();
             
                foreach (var temp in classList)
                    treeView_ProdutFile.Nodes[0]?.FirstNode?.Nodes?.Add(temp);
            }
            treeView_ProdutFile.Nodes[0].ExpandAll();
            treeView_ProdutFile.Nodes[1].Expand();

        }
        //权限变更 更新
        public void ChangedUserRight(User CurrentUser)
        {

            if (userRight == CurrentUser._userRight)
                return;
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => ChangedUserRight(CurrentUser)));
            }
            else
            {
                UpdateProductList();
                UpdataParamDataGridViewClass(CurrentUser);
                FlushParamToScreen(CurrentUser, "all");
                GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
            }
        }
        //载入文件 更新
        void LoadProductFile(string strFile)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action(() => ChangedUserRight(sys.g_User)));
            }
            else
            {
                UpdateProductList();
                UpdataParamDataGridViewClass(sys.g_User);
                FlushParamToScreen(sys.g_User, "all");
                label_CurrentFile.Text = strFile;
                BtnLoad.Enabled = true;
            }
        }
        private void UpdateProductList()
        {
            treeView_ProdutFile.Nodes.Clear();
            treeView_ProdutFile.Nodes.Add("当前产品".Trim());
            treeView_ProdutFile.Nodes.Add("产品选择".Trim());

            if (ParamSetMgr.GetInstance().CurrentProductFile != null && ParamSetMgr.GetInstance().CurrentProductFile != "")
            {
                treeView_ProdutFile.Nodes[nIndexOfName].Nodes.Add(ParamSetMgr.GetInstance().CurrentProductFile);
               // treeView_ProdutFile.Nodes[nIndexOfName].ImageIndex = 0;
            }
            DirectoryInfo[] dirInfo = ParamSetMgr.GetInstance().EnumProductFile();
            int pos;
            for (int i = 0; dirInfo != null && i < dirInfo.Length; i++)
            {
                pos = dirInfo[i].FullName.LastIndexOf("\\");
                string str = dirInfo[i].FullName.Substring(pos + 1, dirInfo[i].FullName.Length - pos - 1);
                if (str != ParamSetMgr.GetInstance().CurrentProductFile)
                    treeView_ProdutFile.Nodes[1].Nodes.Add(str);
               
            }
          
        }

        private void Form_ParamSet_Load(object sender, EventArgs e)
        {
            sys.g_eventRightChanged += ChangedUserRight;
            ChangedUserRight(sys.g_User);
            ParamSetMgr.GetInstance().m_eventLoadProductFile += LoadProductFile;
            label_CurrentFile.Text = ParamSetMgr.GetInstance().CurrentProductFile;
            LoadProductFile(ParamSetMgr.GetInstance().CurrentProductFile);
            dataGridView_Param.DataError += DataGridView_Param_DataError;
            LanguageHelp.GetInstance().Funtion_TransLate(this.Name);
            GlobalVariable.g_eventStationStateChanged += GlobalVariable_g_eventStationStateChanged;
            GlobalVariable.g_eventControlModeChanged += GlobalVariable_g_eventControlModeChanged;

            GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
        }
        private void GlobalVariable_g_eventControlModeChanged(ControlMode currRunMode)
        {
            GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
        }

        private void GlobalVariable_g_eventStationStateChanged(StationState currState)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action(() => GlobalVariable_g_eventStationStateChanged(currState)));
            else
            {
                if ((GlobalVariable.g_StationState == StationState.StationStateEmg || GlobalVariable.g_StationState == StationState.StationStateStop)
                    &&
                    GlobalVariable.g_ControlMode != ControlMode.Auto)
                {
                    dataGridView_Param.Enabled = true;
                    PanRecipeChange.Enabled = true;
                }
                else
                {
                    dataGridView_Param.Enabled = false;
                    PanRecipeChange.Enabled = false;
                }
            }

        }

        private void DataGridView_Param_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            //throw new NotImplementedException();
        }

        private void BtnDel_Click(object sender, EventArgs e)
        {
            if (treeView_ProdutFile.SelectedNode == null)
            {
                UIMessageBox.ShowError("请选择要添加子节点的节点！".Trim());
                return;
            }
            if (treeView_ProdutFile.SelectedNode == treeView_ProdutFile.Nodes[0])
            {
                UIMessageBox.ShowError("不能删除根结点！".Trim());
                return;
            }
            if (ParamSetMgr.GetInstance().CurrentWorkDir == "")
            {
                UIMessageBox.ShowError("当前产品目录文件夹！".Trim());
                return;
            }
            bool bFind = Directory.Exists(ParamSetMgr.GetInstance().CurrentWorkDir);
            if (!bFind)
            {
                UIMessageBox.ShowError("当前产品目录文件夹！".Trim());
                return;
            }
            if (treeView_ProdutFile.SelectedNode == treeView_ProdutFile.Nodes[0].Nodes[0])
            {
                UIMessageBox.ShowError("当前产品文件不能删除，请先载入！".Trim());
                return;
            }
            string strdirPath = ParamSetMgr.GetInstance().CurrentWorkDir + ("\\") + treeView_ProdutFile.SelectedNode.Text;
            if (!UIMessageBox.ShowAsk($"是否确定删除{treeView_ProdutFile.SelectedNode.Text}"))
                return;
            if (Directory.Exists(strdirPath))
            {
                // DeleteFolder(strdirPath);
                FileOpert.DeleteFolder(strdirPath);

            }
            treeView_ProdutFile.SelectedNode.Remove();
        }

        private void BtnLoad_Click(object sender, EventArgs e)
        {
            if (treeView_ProdutFile.SelectedNode == null)
            {
                UIMessageBox.ShowError("请选择要载入的文件！".Trim());
                return;
            }
            if (treeView_ProdutFile.SelectedNode == treeView_ProdutFile.Nodes[0])
            {
                UIMessageBox.ShowError("选择错误！".Trim());
                return;
            }
            if (ParamSetMgr.GetInstance().CurrentWorkDir == "")
            {
                UIMessageBox.ShowError("当前产品目录文件夹为空！".Trim());
                return;
            }
            bool bFind = Directory.Exists(ParamSetMgr.GetInstance().CurrentWorkDir);
            if (!bFind)
            {
                UIMessageBox.ShowError("当前产品目录文件夹不存在！".Trim());
                return;
            }
            if (ParamSetMgr.GetInstance().CurrentProductFile == treeView_ProdutFile.SelectedNode.Text)
                return;
            string strOldFile = ParamSetMgr.GetInstance().CurrentProductFile;
            if (!File.Exists(ParamSetMgr.GetInstance().CurrentWorkDir + ("\\") + treeView_ProdutFile.SelectedNode.Text + ("\\") + treeView_ProdutFile.SelectedNode.Text + (".xml")))
                return;
            if (ParamSetMgr.GetInstance().CurrentProductFile != treeView_ProdutFile.SelectedNode.Text)
                ParamSetMgr.GetInstance().CurrentProductFile = treeView_ProdutFile.SelectedNode.Text;

            ConfigToolMgr.GetInstance().SaveProductFile();
            CommonTools.ConfigToolMgr.GetInstance().ReadUserParam(Param_System.Instance);
            ////删除之前登陆产品文件名
            //if (treeView_ProdutFile.Nodes.Count > 0 && treeView_ProdutFile.Nodes[0].GetNodeCount(true) > 0)
            //    treeView_ProdutFile.Nodes[0].Nodes[0].Remove();
            //treeView_ProdutFile.Nodes[0].Nodes.Add(ParamSetMgr.GetInstance().CurrentProductFile);

            ////删除当前登陆产品文件名
            //string strNewFile = ParamSetMgr.GetInstance().CurrentProductFile;
            //for (int i = 0; i < treeView_ProdutFile.Nodes[1].Nodes.Count; i++)
            //{
            //    if (treeView_ProdutFile.Nodes[1].Nodes[i].Text == strNewFile)
            //    {
            //        treeView_ProdutFile.Nodes[1].Nodes[i].Collapse();
            //        treeView_ProdutFile.Nodes[1].Nodes.Remove(treeView_ProdutFile.Nodes[1].Nodes[i]);
            //    }
            //}
            //treeView_ProdutFile.Update();

            //if (treeView_ProdutFile.Nodes[0].FirstNode != null && treeView_ProdutFile.Nodes[0].FirstNode.Name != null && treeView_ProdutFile.Nodes[0].FirstNode.Text != "")
            //{
            //    List<string> classList = ParamSetMgr.GetInstance().GetParamClassList();
            //    treeView_ProdutFile.Nodes[0]?.FirstNode?.Nodes?.Clear();
            //    foreach (var temp in classList)
            //        treeView_ProdutFile.Nodes[0]?.Nodes[0]?.Nodes.Add(temp);
            //}
            //treeView_ProdutFile.Nodes[0].ExpandAll();
            ////增加之前登陆产品文件名
            //treeView_ProdutFile.Nodes[1].Nodes.Add(strOldFile);
        }

        protected void DeleteTreeNode2(TreeNode node)
        {
            //后序遍历
            foreach (TreeNode child in node.Nodes)
            {
                DeleteTreeNode2(child);
            }
            node.Remove();
        }

        private void AddNewClass_Click(object sender, EventArgs e)
        {
            
            if (treeView_ProdutFile.Nodes[0].Name == null || treeView_ProdutFile.Nodes[0].FirstNode == null || treeView_ProdutFile.Nodes[0].FirstNode.Text == "")
                return;
            string value = "";
            string desc = "请输入分类名称：".Trim();
            if (UIInputDialog.InputStringDialog(this, ref value, true, desc))
            {
                if (value != "")
                {
                    if (value == "all")
                        return;
                    DataGridViewComboBoxColumn combox = (DataGridViewComboBoxColumn)dataGridView_Param.Columns[6];
                    if (!combox.Items.Contains(value))
                    {
                        combox.Items.Add(value);
                        treeView_ProdutFile.Nodes[0].Nodes[0].Nodes.Add(value);
                    }

                }
            }
        }

        private void treeView_ProdutFile_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView_ProdutFile.Nodes[0] == null || treeView_ProdutFile.Nodes[0].Nodes.Count == 0 || treeView_ProdutFile.Nodes[0].Nodes[0] == null)
                return;
            if (e.Node == null || e.Node.Parent == null)
                return;
            if (e.Node.Parent.Text == treeView_ProdutFile.Nodes[0].Nodes[0].Text)
            {
                //  e.Node.Text
                FlushParamToScreen(sys.g_User, e.Node.Text);
            }
            if (e.Node.Parent.Text == "当前产品".Trim())
            {
                FlushParamToScreen(sys.g_User, "all");
            }
        }

        public void DevelopModleChanged(bool bChange)
        {
            if (this.InvokeRequired)
            {

                this.BeginInvoke(new Action(() => { DevelopModleChanged(bChange); }));
            }
            else
            {
                if (dataGridView_Param.Columns.Count > nIndexOfbIsStartCheck)
                {
                    if (bChange)
                    {
                        dataGridView_Param.Columns[nIndexOfbIsStartCheck].Width = 50;
                        dataGridView_Param.Columns[nIndexOfbIsStartCheck].Visible = true;
                    }
                    else
                    {
                        dataGridView_Param.Columns[nIndexOfbIsStartCheck].Width = 0;
                        dataGridView_Param.Columns[nIndexOfbIsStartCheck].Visible = true;
                    }

                }
            }
          
        

        }
        string currentParamClass = "all";
        public void FlushParamToScreen(User CurrentUser, string strParmClass)
        {
            userRight = CurrentUser._userRight;
            dataGridView_Param.Rows.Clear();
            //ParamSetMgr.GetInstance().ClearAllParamClassList();
            Dictionary<string, ParamSet> allparam = ParamSetMgr.GetInstance().GetFields<ParamSet>(Param_System.Instance);

            int index = 0;
            foreach (var temp in allparam)
            {
                currentParamClass = strParmClass;
                if (strParmClass != "all")
                    if (temp.Value._ParamClass != strParmClass)
                        continue;
                   dataGridView_Param.Rows.Add(temp.Key, temp.Value._enuValType.ToString().Trim(),
                     temp.Value._strParamVal, temp.Value._strParamValMax, temp.Value._strParamValMin,
                     temp.Value._ParamRight.ToString(), temp.Value._ParamClass.ToString(), temp.Value.b_IsStartCheck);

                if ((int)(UserRight)Enum.Parse(typeof(UserRight), dataGridView_Param.Rows[index].Cells[5].Value.ToString()) <= (int)CurrentUser._userRight)
                {
                    //dataGridView_Param.Rows[index].ReadOnly = false;
                    dataGridView_Param.Rows[index].Cells[0].ReadOnly = true;
                    dataGridView_Param.Rows[index].Cells[1].ReadOnly = true;
                    dataGridView_Param.Rows[index].Cells[2].ReadOnly = false;
                    dataGridView_Param.Rows[index].Cells[3].ReadOnly = false;
                    dataGridView_Param.Rows[index].Cells[4].ReadOnly = false;
                    dataGridView_Param.Rows[index].Cells[5].ReadOnly = false;
                    dataGridView_Param.Rows[index].Cells[6].ReadOnly = false;
                    dataGridView_Param.Rows[index].Cells[7].ReadOnly = false;
                    dataGridView_Param.Rows[index].Visible = true;
                }
                else
                {
                    dataGridView_Param.Rows[index].Cells[0].ReadOnly = true;
                    dataGridView_Param.Rows[index].Cells[1].ReadOnly = true;
                    dataGridView_Param.Rows[index].Cells[2].ReadOnly = true;
                    dataGridView_Param.Rows[index].Cells[3].ReadOnly = true;
                    dataGridView_Param.Rows[index].Cells[4].ReadOnly = true;
                    dataGridView_Param.Rows[index].Cells[5].ReadOnly = true;
                    dataGridView_Param.Rows[index].Cells[6].ReadOnly = true;
                    dataGridView_Param.Rows[index].Cells[7].ReadOnly = true;
                    dataGridView_Param.Rows[index].Visible = true;
                }

                index++;
            }

        }

        private void dataGridView_Param_Click(object sender, EventArgs e)
        {
            try
            {
                int RowIndex = dataGridView_Param.CurrentCell.RowIndex;
                int ColumnIndex = dataGridView_Param.CurrentCell.ColumnIndex;
                if (ColumnIndex >= 0 && RowIndex >= 0)
                {
                    richTxt_参数说明.Text = $"参数名:{ dataGridView_Param[0, RowIndex].Value}" + Environment.NewLine;
                    richTxt_参数说明.Text += $"当前值:{ dataGridView_Param[2, RowIndex].Value}" + Environment.NewLine;
                    richTxt_参数说明.Text += $"允许最大值:{ dataGridView_Param[3, RowIndex].Value}" + Environment.NewLine;
                    richTxt_参数说明.Text += $"允许最小值:{ dataGridView_Param[4, RowIndex].Value}" + Environment.NewLine;
                    if (dataGridView_Param[0, RowIndex].Value == null)
                        return;
                    var de = ParamSetMgr.GetInstance().paramValue?.Find(p => p.ParamName == (dataGridView_Param[0, RowIndex].Value).ToString().Trim());
                    if (de == null)
                    {
                        richTxt_参数说明.Text += $"参数描述:还未添加描述，请在Description.xml中添加" + Environment.NewLine;
                    }
                    else
                    {
                        richTxt_参数说明.Text += $"参数描述:{ de.Description}" + Environment.NewLine;
                    }

          
                }
            }  
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                return;
            }

        }
   
        private static void CopyDir(string srcPath, string aimPath, string productName, string newName)
        {
            //try
            {
                if (aimPath[aimPath.Length - 1] != System.IO.Path.AltDirectorySeparatorChar)
                {
                    aimPath += System.IO.Path.DirectorySeparatorChar;
                }
                if (!System.IO.Directory.Exists(aimPath))
                {
                    Directory.CreateDirectory(aimPath);
                }
                string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
                foreach (string file in fileList)
                {
                    if (System.IO.Directory.Exists(file))
                    {
                        CopyDir(file, aimPath + Path.GetFileName(file), productName, newName);
                    }
                    else
                    {
                        //try
                        {
                            string fileFullName = aimPath + Path.GetFileName(file);
                            if (productName == Path.GetFileName(file))
                            {
                                File.Copy(file, $"{aimPath}\\{newName}.xml", true);
                            }

                            else
                            {
                                File.Copy(file, fileFullName, true);
                            }

                        }
                        //catch { }
                    }
                }
            }
            //catch
            {
            }
        }

        private void Form_ParamSet_Resize(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView_Param.Columns.Count; i++)
            {
                dataGridView_Param.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
            panDGV.Width = panMain.Width - panRich.Width;
        }

        public void ChangeDataGridViewCellBackColor(DataGridView dataGridView, int RowIndex,int  ColumnIndex)
        {
            DataGridViewRow dr = (dataGridView as DataGridView).Rows[RowIndex];
            dr.Cells[ColumnIndex].Style.BackColor = Color.Yellow;
            dataGridView_Param.Invalidate(dr.Cells[ColumnIndex].ContentBounds);
            dr.Cells[ColumnIndex].Selected = false;
        }
        private void dataGridView_Param_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int RowIndex = dataGridView_Param.CurrentCell.RowIndex;
                if ((int)(UserRight)Enum.Parse(typeof(UserRight), dataGridView_Param.Rows[RowIndex].Cells[5].Value.ToString()) > (int)sys.g_User._userRight)
                    return;
                int ColumnIndex = dataGridView_Param.CurrentCell.ColumnIndex;
                if (ColumnIndex == 2 || ColumnIndex == 3 || ColumnIndex == 4)
                {
                    string valType = ColumnIndex == 2 ? "参数值" : ColumnIndex == 3 ? " 最大值" : "最小值";
                    string oldData = dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString();
                    string paramname = dataGridView_Param[0, RowIndex].Value.ToString();
                    if (ColumnIndex == 2 && (dataGridView_Param[1, RowIndex].Value != null &&
                         dataGridView_Param[3, RowIndex].Value != null &&
                         dataGridView_Param[4, RowIndex].Value != null
                         ))
                    {

                        InputDataToDataGridView(RowIndex, ColumnIndex, dataGridView_Param[3, RowIndex].Value.ToString(), dataGridView_Param[4, RowIndex].Value.ToString());
                        btnSave.Focus();
                        string newData = dataGridView_Param[ColumnIndex, RowIndex].Value.ToString();
                        UIMessageTipHelper.ShowInfoTip(dataGridView_Param.GetParentForm(), $"参数：{paramname}  {valType}被修改 原值：{oldData} --> 现值:{newData}", TipStyle.Gray, 1500);
                    }
                    if (dataGridView_Param[1, RowIndex].Value != null && (ColumnIndex == 3 || ColumnIndex == 4))
                    {
                        InputDataToDataGridView(RowIndex, ColumnIndex, "", "");
                        btnSave.Focus();
                        string newData = dataGridView_Param[ColumnIndex, RowIndex].Value.ToString();
                        UIMessageTipHelper.ShowInfoTip(dataGridView_Param.GetParentForm(), $"参数：{paramname} {valType}被修改 原值：{oldData} --> 现值:{newData}", TipStyle.Gray, 1500);

                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
            }
        }

        private void InputDataToDataGridView(int RowIndex, int ColumnIndex, string  max,string  min)
        {
            bool bRtnInput = false;
            switch (Enum.Parse(typeof(ParamSetUnit), dataGridView_Param[1, RowIndex].Value?.ToString()))
            {

                case ParamSetUnit.intUnit:
                    int nMax = max != "" ? max.ToInt() : int.MaxValue;
                    int nMin = min != "" ? min.ToInt() : int.MinValue;
             
                    int valueInt = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToInt();
                    bRtnInput = UIInputDialog.InputIntegerDialog(this, ref valueInt, true, "请输入数字：");
                    if (bRtnInput)
                    {
                      
                        if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString().ToInt() != valueInt)
                        {
                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                            dataGridView_Param[ColumnIndex, RowIndex].Value = valueInt;
                        }
                    }
                    int dOldValint = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToInt();
                    if (valueInt == dOldValint) bRtnInput = true;
                    break;
                case ParamSetUnit.doubleUnit:
                    double dMax = max != "" ? max.ToDouble() : double.MaxValue;
                    double dMin = min != "" ? min.ToDouble() : double.MinValue;
                    double valueDouble = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToDouble();
                    bRtnInput = UIInputDialog.InputDoubleDialog(this, ref valueDouble, 3, true, "请输入数字：");
                    if (bRtnInput)
                    {
                        if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString().ToDouble()!= valueDouble)
                        {
                           
                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                            dataGridView_Param[ColumnIndex, RowIndex].Value = valueDouble;
                        }
                    }
                    double dOldValdouble= dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToDouble();
                    if (valueDouble == dOldValdouble)
                        bRtnInput = true;
                    break;
                case ParamSetUnit.boolUnit:
                    int selectIndex = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToUpper() == "TRUE" ? 0 : 1;
                    List<string> items = new List<string>() { "True", "False" };
                    bRtnInput = this.ShowSelectDialog(ref selectIndex, items,"是否选择".Trim(),"", UIStyle.Blue);
                    if (bRtnInput)
                    {
                        if(dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString()!= items[selectIndex])
                        {
                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                            dataGridView_Param[ColumnIndex, RowIndex].Value = items[selectIndex];
                        }
                    }
                    if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString() == items[selectIndex])
                        bRtnInput = true;


                    break;
                case ParamSetUnit.stringUnit:
                    string valueString = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? "" : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString();
                    bRtnInput = UIInputDialog.InputStringDialog(this, ref valueString, false, "请输入字符：");
                    if (bRtnInput)
                    {
                        if(dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString()!= valueString)
                        {
                            dataGridView_Param[ColumnIndex, RowIndex].Value = valueString;
                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                        }
                    }
                    if (valueString == dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString())
                        bRtnInput = true;

                    break;

            }
            if (!bRtnInput)
                this.ShowMessageDialog("输入值错误，可能超出上下限，请检查", "Err", true, UIStyle.Blue);
        }

        List<string> ItemName = new List<string>();
        private bool Check()
        {
            try
            {
                ItemName.Clear();
                for (int i = 0; i < dataGridView_Param.Rows.Count - 1; i++)
                {
                    string name = dataGridView_Param.Rows[i].Cells[0].Value.ToString().Trim();
                    string sort = dataGridView_Param.Rows[i].Cells[6].Value.ToString().Trim();
                    string type = dataGridView_Param.Rows[i].Cells[1].Value.ToString().Trim();
                    string value = dataGridView_Param.Rows[i].Cells[2].Value.ToString().Trim();
                    string Max = dataGridView_Param.Rows[i].Cells[3].Value.ToString().Trim();
                    string Min = dataGridView_Param.Rows[i].Cells[4].Value.ToString().Trim();
                    dynamic v; dynamic vMax; dynamic vMin;

                    if (type == "boolUnit")
                    {
                        if (value.ToLower() != "true" && value.ToLower() != "false")
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，请输入false或者true");
                            return false;
                        }
                        if (Max.ToLower() != "true" && Max.ToLower() != "false")
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，请输入false或者true");
                            return false;
                        }
                        if (Min.ToLower() != "true" && Min.ToLower() != "false")
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，请输入false或者true");
                            return false;
                        }
                    }
                    else if (type == "intUnit")
                    {

                        if (value.Contains("."))
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，有小数点");
                            return false;
                        }
                        if (Max.Contains("."))
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，有小数点");
                            return false;
                        }
                        if (Min.Contains("."))
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，有小数点");
                            return false;
                        }
                        try
                        {
                            v = Convert.ToInt32(value);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMax = Convert.ToInt32(Max);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMin = Convert.ToInt32(Min);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，请输入int类型数据");
                            return false;
                        }
                        if (v > vMax || v < vMin)
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，不在规格内");
                            return false;
                        }
                    }
                    else if (type == "doubleUnit")
                    {
                        try
                        {
                            v = Convert.ToDouble(value);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMax = Convert.ToDouble(Max);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMin = Convert.ToDouble(Min);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，请输入int类型数据");
                            return false;
                        }
                        if (v > vMax || v < vMin)
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，不在规格内");
                            return false;
                        }

                    }
                    else if (type == "stringUnit")
                    {

                    }
                    if (ItemName.Contains(name))
                    {
                        UIMessageBox.ShowError($"第{i}行存在重名参数{name},请检查");
                        return false;
                    }
                    ItemName.Add(name);
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                return false;
            }

        }

        private void OherSave_Click(object sender, EventArgs e)
        {
            bool bFind = Directory.Exists(ParamSetMgr.GetInstance().CurrentWorkDir);
            if (!bFind)
            {
                UIMessageBox.ShowError("没有产品文件，请设置");
                return;
            }
            string valueString = "";
            bool  bRtnInput = UIInputDialog.InputStringDialog(this, ref valueString, true, "请输入名字：");
            if (bRtnInput)
            {
                if (valueString == "" || valueString.Trim() == "")
                {
                    UIMessageBox.ShowError("产品名称为空！");
                    return;
                }
                string OldDir = $"{ParamSetMgr.GetInstance().CurrentWorkDir}\\{ParamSetMgr.GetInstance().CurrentProductFile}\\";
                string NewDir = $"{ParamSetMgr.GetInstance().CurrentWorkDir}\\{valueString.Trim()}\\";
                if (Directory.Exists(NewDir))
                {

                    this.ShowMessageDialog("该产品已存在，请检查", "Err", true, UIStyle.Blue);
                   // UIMessageBox.ShowError("该产品已存在！");
                    return;
                }
                Directory.CreateDirectory($"{NewDir}");
                CopyDir(OldDir, NewDir, $"{ParamSetMgr.GetInstance().CurrentProductFile}.xml", $"{ valueString.Trim()}");
                treeView_ProdutFile.Nodes[1].Nodes.Add(valueString.Trim());
                treeView_ProdutFile.ExpandAll();
           
            }
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!this.ShowAskDialog("是否保存该系统参数！", UIStyle.Blue)) return;

            if (!Check())
            {
                return;
            }        
            string currentProductFile = ParamSetMgr.GetInstance().CurrentWorkDir + ("\\") + ParamSetMgr.GetInstance().CurrentProductFile + ("\\") + ParamSetMgr.GetInstance().CurrentProductFile + (".xml");
            if (!Directory.Exists(ParamSetMgr.GetInstance().CurrentWorkDir + ("\\") + ParamSetMgr.GetInstance().CurrentProductFile))
            {
                UIMessageBox.ShowError("没有新建产品文件夹，请新建或另存");
                return;
            }
            Dictionary<string, ParamSet> dic_Param =ParamSetMgr.GetInstance().GetFields<ParamSet>(Param_System.Instance);
            if (dic_Param == null)
                return;
            Dictionary<string, ParamSet> staParam_New = dic_Param;
            for (int i = 0; i < dataGridView_Param.RowCount; i++)
            {
                if (dataGridView_Param.Rows[i].Cells[0].Value != null && dataGridView_Param.Rows[i].Cells[0].Value.ToString() != "")
                {
                    string strParamName = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name, dataGridView_Param.Rows[i].Cells[nIndexOfName].Value.ToString());
                    string strValType = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfUnit].Value.ToString());
                    string strParamVal = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name, dataGridView_Param.Rows[i].Cells[nIndexOfVal].Value.ToString());
                    string strParamValMax = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfMax].Value.ToString());
                    string strParamValMin = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfMin].Value.ToString());
                    string strParamRight = dataGridView_Param.Rows[i].Cells[nIndexOfRight].Value.ToString();
                    string strParamClass = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfClass].Value.ToString());
                    ParamSet paramSet = new ParamSet()
                    {
                        _strParamUnit = strParamName,
                        _enuValType = dataGridView_Param.Rows[i].Cells[nIndexOfUnit].Value == null ? ParamSetUnit.doubleUnit : (ParamSetUnit)Enum.Parse(typeof(ParamSetUnit), strValType),
                        _strParamVal = dataGridView_Param.Rows[i].Cells[nIndexOfVal].Value == null ? "0" : strParamVal,
                        _strParamValMax = dataGridView_Param.Rows[i].Cells[nIndexOfMax].Value == null ? "0" : strParamValMax,
                        _strParamValMin = dataGridView_Param.Rows[i].Cells[nIndexOfMin].Value == null ? "0" : strParamValMin,
                        _ParamRight = dataGridView_Param.Rows[i].Cells[nIndexOfRight].Value == null ? UserRight.Operator : (UserRight)Enum.Parse(typeof(UserRight), strParamRight),
                        _ParamClass = dataGridView_Param.Rows[i].Cells[nIndexOfClass].Value == null ? "综合" : strParamClass,
                        b_IsStartCheck =Convert.ToBoolean(dataGridView_Param.Rows[i].Cells[nIndexOfbIsStartCheck].Value)
                    };
                    if (paramSet._enuValType == ParamSetUnit.boolUnit)
                    {
                        paramSet._strParamVal = Convert.ToBoolean(paramSet._strParamVal);
                        paramSet._strParamValMax = Convert.ToBoolean(paramSet._strParamValMax);
                        paramSet._strParamValMin = Convert.ToBoolean(paramSet._strParamValMin);
                    }
                    else if (paramSet._enuValType == ParamSetUnit.doubleUnit)
                    {
                        paramSet._strParamVal = Convert.ToDouble(paramSet._strParamVal);
                        paramSet._strParamValMax = Convert.ToDouble(paramSet._strParamValMax);
                        paramSet._strParamValMin = Convert.ToDouble(paramSet._strParamValMin);
                    }
                    else if (paramSet._enuValType == ParamSetUnit.intUnit)
                    {
                        paramSet._strParamVal = Convert.ToInt32(paramSet._strParamVal);
                        paramSet._strParamValMax = Convert.ToInt32(paramSet._strParamValMax);
                        paramSet._strParamValMin = Convert.ToInt32(paramSet._strParamValMin);
                    }
                    else if (paramSet._enuValType == ParamSetUnit.stringUnit)
                    {
                        paramSet._strParamVal = Convert.ToString(paramSet._strParamVal);
                        paramSet._strParamValMax = Convert.ToString(paramSet._strParamValMax);
                        paramSet._strParamValMin = Convert.ToString(paramSet._strParamValMin);
                    }
                    staParam_New[strParamName] = paramSet;
                    string str_PointInfo = $"站位名称：{this.Name}，参数名称：{strParamName}，参数值：{strParamVal}";
                }
            }
            FieldInfo[] list_Field = Param_System.Instance.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            if (list_Field.Length <= 0) return;
            foreach (var item in list_Field)
            {
                string str_Name = item.Name;
                for (int i = 0; i < staParam_New.Count; i++)
                {
                    if (str_Name == staParam_New.Keys.ToList()[i])
                    {
                        ParamSet paramOld = (ParamSet)item.GetValue(Param_System.Instance);
                        ParamSet paramNew = staParam_New.Values.ToList()[i];
                        if (paramOld._strParamVal != paramNew._strParamVal)
                            BaseDll.DeviceDataCollect.GetInstance().Function_ParamChangeLog("系统", str_Name,Convert.ToString(paramOld._strParamVal), Convert.ToString(paramNew._strParamVal), "值");
                        if (paramOld._strParamValMax != paramNew._strParamValMax)
                            BaseDll.DeviceDataCollect.GetInstance().Function_ParamChangeLog("系统", str_Name, Convert.ToString(paramOld._strParamValMax), Convert.ToString(paramNew._strParamValMax), "最大值");
                        if (paramOld._strParamValMin != paramNew._strParamValMin)
                            BaseDll.DeviceDataCollect.GetInstance().Function_ParamChangeLog("系统", str_Name, Convert.ToString(paramOld._strParamValMin), Convert.ToString(paramNew._strParamValMin), "最小值");

                        item.SetValue(Param_System.Instance, staParam_New.Values.ToList()[i]);
                    }
                }
            }
            ParamSetMgr.GetInstance().SaveParam(Param_System.Instance);
            for (int i = 0; i < dataGridView_Param.RowCount; i++)
            {    
                
                if (dataGridView_Param.Rows[i].Cells[nIndexOfVal].Style.BackColor == Color.Yellow)
                        dataGridView_Param.Rows[i].Cells[nIndexOfVal].Style.BackColor = Color.White;
                    if (dataGridView_Param.Rows[i].Cells[nIndexOfMax].Style.BackColor == Color.Yellow)
                        dataGridView_Param.Rows[i].Cells[nIndexOfMax].Style.BackColor = Color.White;
                    if (dataGridView_Param.Rows[i].Cells[nIndexOfMin].Style.BackColor == Color.Yellow)
                        dataGridView_Param.Rows[i].Cells[nIndexOfMin].Style.BackColor = Color.White;
            }


        }
    }



}
